#include "server.h"

int server_worker(int netfd, MYSQL *mysql)
{
    // 第一次连接时初始化server_path、client_path(整个网盘连接时最开始初始化一次)
    azu_factory_t factor;
    //清空结构体factor
    bzero(&factor, sizeof(factor));
    //初始化后的mysql赋值结构体中的server_db
    factor.server_db = mysql;
    //初始化server.path、client.path
    char addr[1024]={0};
    getcwd(addr,sizeof(addr));
    strcpy(factor.server_path,addr);// 赋值一开始的服务端绝对路径
    strcpy(factor.client_path,"/");// 赋值一开始的客户端看见的虚拟路径

    // 开始循环接受命令
    while(1)
    {
        char buf[4096];
        bzero(buf, sizeof(buf));        
        ssize_t sret = recv(netfd, buf, sizeof(buf), 0);// 接受用户发的消息
        if(sret == 0)
        {
            printf("客户端已断开！\n");
            break;
        }

        char *command = strtok(buf, " ");// 存放用户发送的“命令 路径/文件”中的“命令”
        char *path = strtok(NULL, "\n");// 存放用户发送“命令 路径/文件”中的“路径/文件”

        bzero(factor.command,sizeof(factor.command));// 清空factor.command
        bzero(factor.input_path,sizeof(factor.input_path));// 清空input_path

        if (path == NULL)// 若用户只发送“命令”未跟路径或文件，如“ls”、“pwd”
        {
            strncpy(factor.command, command, strlen(command) - 1);// 赋值factor.command（去除\n）
        }
        else
        {
            strcpy(factor.command, command);// 赋值factor.command
            strcpy(factor.input_path, path);// 赋值input_path
        }

        printf("客户端传来的命令 : %s ", factor.command);
        printf("客户端传来的路径 : %s\n", factor.input_path);
        
        command_execute(netfd, &factor);
        printf("命令结束后的客户端绝对路径 : %s ", factor.server_path);
    }
    return 0;
}

int command_execute(int netfd, azu_factory_t *factor)
{ 
    int len = strlen(factor->command);
    printf("len = %d\n", len);
    if(len == 2)
    {
        if(strcmp(factor->command,"cd")==0){
            printf("//cd worker\n");                    //
            //worker_cd(netfd, factor);
        }
        else if(strcmp(factor->command,"ls")==0){
            printf("//ls worker\n");
            //worker_ls(netfd,factor);
        }
        else{
            return -1;
        }
    }
    else if(len == 3){
        if(strcmp(factor->command,"pwd")==0){
            printf("//pwd worker\n");                    //
            //worker_pwd(netfd,factor);        
        }
        else{
            return -1;
        }
    }
    else if(len == 4){
        if(strcmp(factor->command,"puts")==0){
            printf("//puts worker\n");                    //
            worker_puts_server(netfd,factor);
        }
        else if(strcmp(factor->command,"gets")==0){
            printf("//gets worker\n");                    //
            //worker_gets_server(netfd,factor);
        }
        else{
            return -1;
        }
    }
    else if(len == 5){
        if(strcmp(factor->command,"mkdir")==0){
            printf("//mkdir worker\n");                    //
            worker_mkdir(netfd,factor);
        }
        else if(strcmp(factor->command,"rmdir")==0){
            //worker_rmdir(netfd,factor);                   //
        }
        else{
            return -1;
        }
    }
    else if(len == 6){
        if(strcmp(factor->command,"remove")==0)
        {
            printf("//remove worker\n");                    //
            //worker_remove(factor);
        }
        else{
            return -1;
        }
    }
    else{
        return -1;
    }

    return 0;
}

int worker_mkdir(int netfd,azu_factory_t *factor){
    //TODO   使用执行命令函数query    执行select语句   查找 path值 = factor->server_path  的父目录
    //保存父目录信息   调用mysql_store_result   (pre_pir)
    //插入行  name = factor—>input_path  type = d pre_pid  path = (拼接 server_paht  /  input_path)
    //   ????user 信息获取
    //  tomb = 0 
    //MD5 == NULL

    if (factor == NULL || factor->server_db == NULL || factor->client_path == NULL || factor->input_path == NULL) 
    {
        printf("Invalid input parameter.\n");
        return -1;
    }

    printf("mkdir start\n");  
    printf("client path : %s\n",factor->client_path);          //             
    int len = strlen(factor->client_path);
    char client_path[len+1];
    strcpy(client_path,factor->client_path);
    //memcpy(client_path,factor->client_path,len);
    printf("client_path : %s\n",client_path);                                              //


    //char* delim = " \t\n";
    //char *filename = strtok(client_path,delim); 
    //printf("filename : %s\n",filename);                                              //

    len = strlen(factor->input_path);
    char input_path[len+1];
    strcpy(input_path,factor->input_path);
    //memcpy(input_path,factor->input_path,len);
    printf("input path : %s\n",input_path);                                                            //

    char sql[1024]={0}; 
    int sret=sprintf(sql,"select pre_pid from files where path ='%s';",client_path);

    if (sret < 0) {
        printf("Failed to generate SQL query.\n");
    } else if (sret >= sizeof(sql)) {
        printf("SQL query is too long.\n");
    } else {
        printf("Generated SQL query: %s\n", sql);
    }

    len = strlen(sql);
    char moresql[len+10];
    memcpy(moresql,sql,len+10);
    printf("len = %d",len);
    printf("moresql   %s\n",moresql);                                                    //sql


    printf("sql 命令语句:  %s\n",sql);                                                    //sql
    //char *sql = "select pre_prd from files where path = factor->client_path";

    int qret = mysql_query(factor->server_db,sql);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(factor->server_db));
        return -1;
    }
    printf("query over\n");                         //
    MYSQL_RES *result = mysql_store_result(factor->server_db);
    MYSQL_ROW row;
    row = mysql_fetch_row(result);
    char *pre_pir=row[0];

    //TODO  区分传入/  和/dir

    char path[1024];
    strcpy(path,client_path);
    printf("%s\n",path);                                                        /////
    //strcat(path,"/");
    //printf("%s\n",path);                                                    //
    strcat(path,input_path);
    printf("%s\n",path);                                                    //

    sret=sprintf(sql,"insert into files(name,type,pre_pid,path,user,tomb) values('%s','d','%s','%s','test2',0);",input_path,pre_pir,path);
    if (sret < 0) {
        printf("Failed to generate SQL query.\n");
    } else if (sret >= sizeof(sql)) {
        printf("SQL query is too long.\n");
    } else {
        printf("Generated SQL query: %s\n", sql);
    }
    qret = mysql_query(factor->server_db,sql);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(factor->server_db));
        return -1;
    }
    return 0;                    
}


int worker_puts_server(int netfd, azu_factory_t *factor){
    

    
    int mdLen=16;
    unsigned char md5[17];
    bzero(&md5, sizeof(md5));
    md5[17]='\0';

    train_t train;
    bzero(&train, sizeof(train));
    recv(netfd, &train.length, sizeof(train.length), MSG_WAITALL);
    recv(netfd, &train.data, train.length, MSG_WAITALL);
    strcpy(md5, train.data);

    char md5_string[mdLen+1];
    for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
        sprintf(&md5_string[i * 2], "%02x", md5[i]);
    }
    //printf("md5_string : %s\n", md5_string);

    char condition1[]="select * from files where tomb<>1 and MD5=";
    char condition2[]=" and PATH =";
    char command[512];
    int status[2]={0};    //mysql状态查询     
                          //第一个tomb<>1且MD5的行数，第一个tomb<>1且MD5且input_path的行数，

    //4 查询mysql，命令拼接，返回行数
    bzero(&command, sizeof(command));
    strcpy(command,condition1);
    strncat(command,"'",sizeof(command)-strlen("'")-1); 
    strncat(command,md5_string,sizeof(command)-strlen(md5_string)-1);
    strncat(command,"'",sizeof(command)-strlen("'")-1);
    strncat(command,";",sizeof(command)-strlen(";")-1); 

    printf("flag =1 , %s\n ",command);
    //tomb<>1且MD5的行数
    MYSQL * mysql = mysql_init(NULL);
    MYSQL * ret = mysql_real_connect(mysql,"localhost","root","321","test",0,NULL,0);
    if(ret == NULL){
        fprintf(stderr,"error:%s\n", mysql_error(mysql));
        return -1;
    }
    char sql[]="";
    strcpy(sql,command);
    int qret = mysql_query(mysql,sql);
    if(qret != 0){
        fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *res = mysql_store_result(mysql);
    printf("total rows = %lu\n", mysql_num_rows(res));

    //获得第一个标志位
    status[0]=mysql_num_rows(res);
    ////////////////////////////////////////////////////////////////
    char path[1024];
    strcpy(path,factor->client_path);
    char sql2[1024]={0};
    int sret=sprintf(sql2,"select * from files where tomb<>1 and MD5='%s' and path='%s';",md5_string,path);
    
    printf("client_path: %s\n",factor->client_path);

    printf("flag =2 , %s\n ",sql2);
    qret = mysql_query(mysql,sql2);
    if(qret != 0){
        fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *res2 = mysql_store_result(mysql);
    printf("total rows = %lu\n", mysql_num_rows(res2));
    status[1]=mysql_num_rows(res2);

    //根据状态判断传递信息
    // status[1]=0;   //条件测试
     status[0]=0;
    if(status[1]==1){   //行数>0 且 当前路径有  相同文件已存在 ；
        //传输状态码1
        bzero(&train, sizeof(train));
        train.length = 1;
        send(netfd, &train, sizeof(train.length)+train.length, MSG_WAITALL);
        int sret = send(netfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);
        return 0;
    }
    else if((status[1]==0)&&(status[0]>=1)){//行数 >0 且当前路径无 相同文件已存在，返回2；
        //传输状态码2
        bzero(&train, sizeof(train));
        train.length = 2;
        send(netfd, &train, sizeof(train.length)+train.length, MSG_WAITALL);
        int sret = send(netfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);
        
        char sql3[1024]={0};

        sprintf(sql3,"select * from files where path='%s';",factor->client_path);

        qret = mysql_query(mysql,sql);
        if(qret != 0){
            fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
            return -1;
        }
        MYSQL_RES *res = mysql_store_result(mysql);
        //printf("total rows = %lu\n", mysql_num_rows(res));
        MYSQL_ROW row;
        row = mysql_fetch_row(res);
        
        int pre_id=atoi(row[0]);
    
        printf("pre_id=%d\n",pre_id);
        printf("\n");
        sret=sprintf(sql,"insert into files(name,type,pre_pid,path,user,tomb,MD5) values('%s','f',%d,'%s','test2',0,'%s');"
                                ,factor->input_path,pre_id,factor->client_path,md5_string);

        qret = mysql_query(mysql,sql);
        if(qret != 0){
            fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
            return -1;
        }   
        
        return 0;       
    }
    else if(status[0]==0){

        bzero(&train, sizeof(train));
        train.length = 3;
        send(netfd, &train, sizeof(train.length)+train.length, MSG_WAITALL);
        int sret = send(netfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);

        //插入一行mysql
        char sql3[1024]={0};
        sprintf(sql3,"select * from files where path='%s';",factor->client_path);

        qret = mysql_query(mysql,sql);
        if(qret != 0){
            fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
            return -1;
        }
        MYSQL_RES *res = mysql_store_result(mysql);
        //printf("total rows = %lu\n", mysql_num_rows(res));
        MYSQL_ROW row;
        row = mysql_fetch_row(res);
        
        int pre_id=atoi(row[0]);
    
        printf("pre_id=%d\n",pre_id);
        printf("\n");
        sret=sprintf(sql,"insert into files(name,type,pre_pid,path,user,tomb,MD5) values('%s','f',%d,'%s','test2',0,'%s');"
                                ,factor->input_path,pre_id,factor->client_path,md5_string);

        qret = mysql_query(mysql,sql);
        if(qret != 0){
            fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
            return -1;
        }   

        

        bzero(&train, sizeof(train));
        int fd = open(factor->input_path, O_WRONLY|O_TRUNC|O_CREAT, 0666);
    
        while (1)
        {
            bzero(&train, sizeof(train));
            recv(netfd, &train.length, sizeof(train.length), MSG_WAITALL);
            if(train.length != 1000)
            {
                printf("train.length = %d\n", train.length);
            }
            if(train.length == 0)
            {
                break;
            }
            recv(netfd, train.data, train.length, MSG_WAITALL);
            write(fd, train.data, train.length);
        }  
        return 0;

    }

    
    




    
}







